package com.mac.intellect_flow.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mac.intellect_flow.constant.CommonConstant;
import com.mac.intellect_flow.enums.ResultCodeEnum;
import com.mac.intellect_flow.except.ServiceException;
import com.mac.intellect_flow.framework.security.context.AuthenticationContextHolder;
import com.mac.intellect_flow.framework.util.JwtUtil;
import com.mac.intellect_flow.framework.util.TokenUtil;
import com.mac.intellect_flow.framework.model.LoginUser;
import com.mac.intellect_flow.redis.util.RedisUtil;
import com.mac.intellect_flow.sys.service.SysConfigService;
import com.mac.intellect_flow.sys.service.SysLoginService;
import com.mac.intellect_flow.sys.service.SysUserService;
import com.mac.intellect_flow.util.Convert;
import com.mac.intellect_flow.util.servlet.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 * 
 * @author mac
 */
@Component
public class SysLoginServiceImpl implements SysLoginService {
    @Autowired
    private TokenUtil tokenService;

    @Resource
    private AuthenticationManager authenticationManager;


    @Autowired
    private SysUserService userService;

    @Autowired
    private SysConfigService configService;

    public SysUserService getUserService() {
        return userService;
    }

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new ServiceException(ResultCodeEnum.LOGIN_ERROR);
            } else {
                throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        String token = tokenService.createToken(loginUser);
        JwtUtil.setRedisUserInfo(null,token,loginUser,true);
        return token;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CommonConstant.CAPTCHA_CODE_KEY + Convert.toStr(uuid, "");
        String captcha = JwtUtil.redisUtil.getCacheObject(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            throw new ServiceException("验证码已失效");
        }
        JwtUtil.redisUtil.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException("请重新滑动");
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"用户名或密码不能为空");
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (CollectionUtil.contains(Arrays.stream(blackStr.split(",")).collect(Collectors.toList()), ServletUtils.getClientIP())) {
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"登录IP地址在黑名单中");
        }
    }
}
